package com.paishen.common.album;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.paishen.common.R;
import com.paishen.common.util.BaseUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import jp.wasabeef.recyclerview.animators.FadeInAnimator;

/**
 * Created by peng on 2016/01/03.
 */
public class PhotoWallActivity extends Activity {

    public static final String EXTRA_SELECTED_PHOTOS = "selected_photos";
    public static final String EXTRA_FOLDER_PATH = "folder_path";

    private RecyclerView viewRecycler;
    private WallAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String folderPath = getIntent().getStringExtra(EXTRA_FOLDER_PATH);
        if (TextUtils.isEmpty(folderPath)) {
            Log.e("PhotoWallActivity", "parent folderPath need to be passed");
            finish();
            return;
        }
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_wall);

        BaseUtil.setStatusBarDarkMode(true, this);

        findViewById(R.id.lay_title).setPadding(0, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? Util.getStatusBarHeight(this) : 0), 0, 0);
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        viewRecycler = (RecyclerView) findViewById(R.id.recycler_photo_wall);
        viewRecycler.setLayoutManager(new GridLayoutManager(this, 3));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter = new WallAdapter(this));
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        viewRecycler.setAdapter(scaleAdapter);
        viewRecycler.setItemAnimator(new FadeInAnimator());
        final int spacing = (int) (3 * getResources().getDisplayMetrics().density + 0.5f);
        viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = spacing;
                outRect.bottom = spacing;
                outRect.right = spacing;
                outRect.left = spacing;
            }
        });
        adapter.set(getAllImagePathsByFolder(folderPath));

        TextView txFinish = (TextView) findViewById(R.id.tx_confirm);
        adapter.setResultView(txFinish);
        txFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> photos = adapter.getSelectedPhotos();
                Intent intent = getIntent();
                intent.putStringArrayListExtra(EXTRA_SELECTED_PHOTOS, photos);
                setResult(photos.size() > 0 ? RESULT_OK : RESULT_CANCELED, intent);
                finish();
            }
        });
    }


    /**
     * 获取指定路径下的所有图片文件。
     */
    private List<String> getAllImagePathsByFolder(String folderPath) {
        File folder = new File(folderPath);
        String[] allFileNames = folder.list();
        if (allFileNames == null || allFileNames.length == 0) {
            return null;
        }

        List<String> imageFilePaths = new ArrayList<>();
        for (int i = allFileNames.length - 1; i >= 0; i--) {
            if (Util.isImage(allFileNames[i])) {
                imageFilePaths.add(folderPath + File.separator + allFileNames[i]);
            }
        }
        return imageFilePaths;
    }

    private static final class WallAdapter extends RecyclerView.Adapter<WallAdapter.ViewHolder> {
        private final List<String> photoList = new ArrayList<>();
        private final ArrayList<String> selectedPhotos = new ArrayList<>();

        private Context appContext;
        private TextView txResult;

        WallAdapter(Context context) {
            appContext = context.getApplicationContext();
        }

        public void setResultView(TextView txResult) {
            this.txResult = txResult;
            txResult.setVisibility(selectedPhotos.size() > 0 ? View.VISIBLE : View.GONE);
        }

        public ArrayList<String> getSelectedPhotos() {
            return selectedPhotos;
        }

        public boolean dealWith(String photo) {
            synchronized (selectedPhotos) {
                if (selectedPhotos.contains(photo)) {
                    selectedPhotos.remove(photo);
                } else {
                    if (selectedPhotos.size() >= 5) {
                        Toast.makeText(appContext, R.string.limit_5, Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    selectedPhotos.add(photo);
                }
            }
            if (txResult != null) {
                if (selectedPhotos.size() > 0) {
                    txResult.setVisibility(View.VISIBLE);
                    txResult.setText(appContext.getString(R.string.confirm_c, String.valueOf(selectedPhotos.size())));
                } else {
                    txResult.setVisibility(View.GONE);
                }
            }
            return true;
        }

        public void set(List<String> dataList) {
            selectedPhotos.clear();
            photoList.clear();
            photoList.addAll(dataList);
            notifyItemRangeChanged(0, getItemCount());
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private String itemData;
            private ImageView imgCover;
            private CheckBox ckState;

            @Override
            public void onClick(View v) {
                if (dealWith(itemData)) {
                    ckState.setChecked(!ckState.isChecked());
                }
            }
        }

        @Override
        public int getItemCount() {
            return photoList.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_photo_wall, viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.ckState = (CheckBox) view.findViewById(R.id.ck_state);
            viewHolder.imgCover = (ImageView) view.findViewById(R.id.img_cover);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            final String photo = photoList.get(i);
            viewHolder.ckState.setChecked(selectedPhotos.contains(photo));
            Glide.with(viewHolder.itemView.getContext()).load(photo).into(viewHolder.imgCover);
            viewHolder.itemData = photo;
        }
    }
}
